<?php
/**
 * Created by PhpStorm.
 * User: xf
 * Date: 2018/6/11
 * Time: 17:51
 */

namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use App\Http\Utils\Time;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class IndexController extends Controller
{
    public function usert()
    {
        return view('home.release.blessing.fileuser', [

        ]);
    }

    /**
     * 首页
     */
    public function index($user_id)
    {
        $activity = DB::table('activity')
            ->where('activity.user_id', '=', $user_id)
            ->select([
                'id',
                'title',
                DB::raw('"activity" as type'),
                'content',
                'create_time',
            ]);

        $vote = DB::table('vote')
            ->where('vote.user_id', '=', $user_id)
            ->select([
                'id',
                'title',
                DB::raw('"vote" as type'),
                'content',
                'create_time',
            ]);
        $blessing = DB::table('blessing')
            ->where('blessing.user_id', '=', $user_id)
            ->select([
                'id',
                DB::raw('"" as title'),
                DB::raw('"blessing" as type'),
                'content',
                'create_time',
            ]);
        $lists = DB::table('notice')
            ->union($activity)
            ->union($vote)
            ->union($blessing)
            ->where('notice.user_id', '=', $user_id)
            ->select([
                'id',
                'title',
                DB::raw('"notice" as type'),
                'content',
                'create_time',
            ])
            ->orderBy('create_time')
            ->get()->toArray();
        if (is_null($lists)) {
            return $this->json('', 417, '还没有数据');
        }
        foreach ($lists as $k => $v) {
            switch (strtolower($v->type)) {
                case 'activity':
                    $lists[$k]->count = DB::table('activity_sign_up')
                        ->where([
                            ['activity_id', '=', $v->id],
                        ])->count();
                    break;
                case 'vote':
                    $count = DB::table('vote_user')
                        ->where([
                            ['vote_id', '=', $v->id],
                        ])->select([
                            'user_id'
                        ])
                        ->distinct()
                        ->get()->toArray();
                    $lists[$k]->count = count($count);
                    break;
                case 'notice':
                    $lists[$k]->count = DB::table('notice_user')
                        ->where([
                            ['notice_id', '=', $v->id],
                        ])->count();;
                    break;
                case 'blessing':
                    $lists[$k]->count = DB::table('leave_message')
                        ->where([
                            ['blessing_id', '=', $v->id],
                        ])->count();;
                    break;
                default:
            }

            $lists[$k]->time = date('Y-m-d', $v->create_time);
        }
        return $this->json($lists);
    }

    /**
     * 详情
     * @param $id
     * @param $type 'notice：通知，activity：活动,vote:投票,blessing:祝福'
     *
     */
    public function details($id, $type)
    {
        $dataList = [];
        switch (strtolower($type)) {
            case 'notice':
                $dataList = $this->noticeDetails($id);
                break;
            case 'activity':
                $dataList = $this->activityDetails($id);
                break;
            case 'vote':
                $dataList = $this->voteDetails($id);
                break;
            case 'blessing':
                $dataList = $this->blessingDetails($id);
                break;

            default:
        }
        if (array_key_exists('code', $dataList) && $dataList['code'] === 417) {
            return $this->json('', 417, $dataList['msg']);
        } else {
            return $this->json($dataList, 200, 'ok');
        }
    }

    //通知
    private function noticeDetails($id)
    {
        $info = DB::table('notice')
            ->join(
                'user',
                'user.id', '=', 'notice.user_id',
                'left'
            )
            ->where([
                ['notice.id', '=', $id]
            ])
            ->select([
                'user.nickName',
                'notice.id',
                'notice.template',
                'notice.title',
                'notice.content',
                'notice.pictures',
                'notice.user_id',
                'notice.reference_number',
                'notice.unit_generation_word',
                'notice.is_forwarding',
                'notice.keyword',
                'notice.update_time',
                'notice.create_time',
            ])
            ->first();
        if (is_null($info)) {
            return ['code' => 417, 'msg' => '没有这条通知'];
        };
        $info->pictures = explode(',', $info->pictures);
        $info->update_time = date('Y-m-d H:s:i', $info->update_time);
        $info->create_time = date('Y-m-d H:s:i', $info->create_time);
        $userList = DB::table('notice_user')
            ->join(
                'leave_message',
                'leave_message.user_id', '=', 'notice_user.user_id',
                'left',
                'leave_message.type="notice" and leave_message.release_id=' . $id
            )
            ->join(
                'user',
                'user.id', '=', 'notice_user.user_id',
                'left'
            )
            ->where([
                ['notice_user.notice_id', '=', $id],
            ])
            ->select([
                'leave_message.id as lm_id',
                'leave_message.content as lm_content',
                'user.nickName',
                'user.avatarUrl',
                'notice_user.create_time',
            ])
            ->get()->toArray();
        if (is_null($userList)) {
            $userList = [];
        }
        foreach ($userList as $k => $v) {
            $userList[$k]->create_time = date('Y-m-d H:i:s', $v->create_time);
        }
        return ['info' => $info, 'user_list' => $userList, 'count' => count($userList)];
    }

    //活动
    private function activityDetails($id)
    {
        $info = DB::table('activity')
            ->join(
                'user',
                'user.id', '=', 'activity.user_id',
                'left'
            )
            ->where([
                ['notice.id', '=', $id]
            ])
            ->select([
                'user.nickName',
                'activity.user_id',
                'activity.id',
                'activity.template',
                'activity.title',
                'activity.content',
                'activity.pictures',
                'activity.reference_number',
                'activity.unit_generation_word',
                'activity.is_forwarding',
                'activity.keyword',
                'activity.people_num',
                'activity.address',
                'activity.address_info',
                'activity.is_user_name',
                'activity.is_user_tel',
                'activity.update_time',
                'activity.create_time',
            ])
            ->first();

        if (is_null($info)) {
            return ['code' => 417, 'msg' => '没有这个活动'];
        };
        $info->pictures = explode(',', $info->pictures);
        $info->update_time = date('Y-m-d H:s:i', $info->update_time);
        $info->create_time = date('Y-m-d H:s:i', $info->create_time);
        $userList = DB::table('activity_sign_up as asu')
            ->join(
                'user',
                'user.id', '=', 'asu.user_id',
                'left'
            )
            ->join(
                'leave_message',
                'leave_message.user_id', '=', 'asu.user_id',
                'left',
                'leave_message.type="activity" and leave_message.release_id=' . $id
            )
            ->where([
                ['activity_id', '=', $id],
            ])
            ->select([
                'leave_message.id as lm_id',
                'leave_message.content as lm_content',
                'asu.activity_id',
                'asu.user_name',
                'asu.user_tel',
                'asu.create_time',
                'user.id as user_id',
                'user.nickName',
                'user.avatarUrl',
            ])
            ->get()->toArray();
        if (is_null($userList)) {
            $userList = [];
        }
        foreach ($userList as $k => $v) {
            $userList[$k]->activity_custom[] = DB::table('activity_custom')
                ->join(
                    'activity_custom_title',
                    'activity_custom_title.id', '=', 'activity_custom.activity_custom_title_id',
                    'left'
                )
                ->where([
                    ['activity_custom.activity_id', '=', $v->activity_id],
                    ['activity_custom.user_id', '=', $v->user_id],
                ])->get()->toArray();
            $userList[$k]->create_time = date('Y-m-d H:i:s', $v->create_time);
        }
        return ['info' => $info, 'user_list' => $userList, 'count' => count($userList)];
    }

    //投票
    private function voteDetails($id)
    {
        $info = DB::table('vote')
            ->join(
                'user',
                'user.id', '=', 'vote.user_id',
                'left'
            )
            ->where([
                ['vote.id', '=', $id]
            ])
            ->select([
                'vote.id',
                'vote.type',
                'vote.title',
                'vote.content',
                'vote.user_id',
                'vote.is_multi_select',
                'vote.min_choose_num',
                'vote.max_choose_num',
                'vote.is_anonymous',
                'vote.is_forwarding',
                'vote.as_of_time',
                'vote.update_time',
                'vote.create_time',
                'user.nickName',
                'user.avatarUrl',
            ])
            ->first();
        if (is_null($info)) {
            return ['code' => 417, 'msg' => '没有这个投票'];
        };
        $info->update_time = date('Y-m-d H:s:i', $info->update_time);
        $info->create_time = date('Y-m-d H:s:i', $info->create_time);
        if (is_numeric($info->as_of_time)) {
            $info->is_overdue = $info->as_of_time > time() ? 'false' : 'true';
        } else {
            $info->is_overdue = strtotime($info->as_of_time) > time() ? 'false' : 'true';
        }

        //参与人数
        $users = DB::table('vote_user')
            ->where([
                ['vote_id', '=', $info->id],
            ])->select([
                'user_id'
            ])
            ->distinct()
            ->get()->toArray();
        $count = count($users);

        //选项
        $voteOptions = DB::table('vote_options')
            ->where('vote_id', '=', $id)
            ->get()->toArray();
        if (is_null($voteOptions)) {
            $voteOptions = [];
        }
        foreach ($voteOptions as $k => $v) {
            $answer = DB::table('vote_user')
                ->where([
                    ['vote_id', '=', $id],
                    ['vote_options_id', '=', $v->id],
                    ['answer', '=', 'true'],
                ])->select([
                    'id'
                ])
                ->distinct()
                ->get()->toArray();
            $voteOptions[$k]->choose_unm = count($answer);
            $voteOptions[$k]->choose_percentage = round(count($answer) / $count, 4);
        }

        return ['info' => $info, 'vote_options' => $voteOptions, 'count' => $count];
    }

    private function blessingDetails($id)
    {
        $info = DB::table('blessing')
            ->join(
                'user',
                'user.id', '=', 'blessing.user_id',
                'left'
            )
            ->where([
                ['blessing.id', '=', $id]
            ])
            ->select([
                'vote.id',
                'vote.content',
                'vote.template',
                'vote.user_id',
                'vote.give_user_name',
                'vote.get_user_name',
                'vote.voice',
                'user.nickName',
                'user.avatarUrl',
            ])
            ->first();
        if (is_null($info)) {
            return ['code' => 417, 'msg' => '没有这条祝福'];
        };
        $info->pictures = explode(',', $info->pictures);
        $info->update_time = date('Y-m-d H:s:i', $info->update_time);
        $info->create_time = date('Y-m-d H:s:i', $info->create_time);
        $userList = DB::table('leave_message')
            ->where([
                ['type', '=', 'notice'],
                ['release_id', '=', $id],
            ])->get()->toArray();
        return ['info' => $info, 'user_list' => $userList, 'count' => count($userList)];
    }

    public function filedel()
    {
        return view('home.release.fieldel', [

        ]);
    }

    /**
     * 记录查看通知，····人数
     * @param Request $request
     * @return array
     */
    public function record(Request $request)
    {
        $data = $request->all();
        switch (strtolower($data['type'])) {
            case 'notice':
                $re = $this->noticeRecord($data['id'], $data['user_id']);
                break;
            default:
                $re = '';
        }
        Log::info('noticeRecord:' . json_encode([
                'old_user_id' => Cache::get('user'),
                'new_user_id' => $data['user_id'],
                'id'          => $data['id'],
                'type'        => $data['type'],
                're'          => $re,
            ]));
    }

    private function noticeRecord($id, $user_id)
    {
        $iscn = DB::table('notice')
            ->where('id', '=', $id)
            ->first();
        if (is_null($iscn)) {
            return ['msg' => '这条通知不存在'];
        }
        $isc = DB::table('notice_user')
            ->where([
                ['notice_id', '=', $id],
                ['user_id', '=', $user_id],
            ])->first();
        if (is_null($isc)) {
            DB::table('notice_user')
                ->insert([
                    'notice_id'   => $id,
                    'user_id'     => $user_id,
                    'create_time' => Time::current(),
                ]);
        }
    }


    /**
     * 删除数据
     * notice|activity|vote|blessing
     */
    public function delRelease($id, $type)
    {
        DB::beginTransaction();
        try {
            switch (strtolower($type)) {
                case 'notice':
                    DB::table('notice')->delete($id);
                    break;
                case 'activity':
                    DB::table('activity')->delete($id);
                    break;
                case 'vote':
                    DB::table('vote')->delete($id);
                    break;
                case 'blessing':
                    DB::table('blessing')->delete($id);
                    break;
                default:
            }
            DB::table('leave_message')
                ->where([
                    ['type', '=', $type],
                    ['release_id', '=', $id],
                ])->delete();
            DB::table('give_a_like')
                ->where([
                    ['type', '=', $type],
                    ['release_id', '=', $id],
                ])->delete();
            DB::commit();
            return $this->json('', 200, 'ok');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->json('', 500, '服务器错误');
        }
    }

    /**
     * 获取模板
     * @param $type notice：通知，activity：活动,vote:投票,blessing:祝福
     */
    public function getTemplate($type)
    {
        $dt = DB::table('template_picture')
            ->where([
                ['type', '=', $type]
            ])->get()->toArray();
        return $this->json($dt, 200, 'ok');
    }
}
